package com.itheima.health.service.impl;

import com.itheima.health.common.RedisConst;
import com.itheima.health.common.RocketMqConst;
import com.itheima.health.message.SmsTask;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.SendCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import java.security.SecureRandom;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@DubboService
@Slf4j
public class SendCodeServiceImpl implements SendCodeService {
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void send(String type, String num) {
        // 短信内容敏感，生产环境下不要输出到日志里
        log.info("[发送短信]phone:{}，content:{}",num,type);
        //生成随机四位数字验证码
        int code = (int) (new SecureRandom().nextDouble() * 8999 + 1000);
        //打印验证码到控制台,模拟发送短信
        log.info("[短信-验证码] code:{}",code);
        //保存验证码到redis中
        redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PRE+type+"_"+num).set(String.valueOf(code),30, TimeUnit.SECONDS);

        // 封装短信发成送任务，放入MQ
//        rocketMQTemplate.convertAndSend(RocketMqConst.TOPIC_SMS_SEND,new SmsTask(num,type));
    }

    @Override
    public void sendOrder(String num, String content) {
        log.info("[短信发送消费者]received message: {},{}", num,content);
        log.info("[短信发送消费者]预约提醒模拟发送，发送中……");
        log.info("[短信发送消费者]预约提醒发送成功");
        //封装成短信放入mq中
//        rocketMQTemplate.convertAndSend(RocketMqConst.TOPIC_ORDER_SEND,new SmsTask(num,content));
    }

    @Override
    public Boolean checkcode(String type, String num, String code) {
//        int savedCode = (int) redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PRE + type + "_" + num).get();
        String savedCode = (String) redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PRE + type + "_" + num).get();
        return code.equals(savedCode);
    }
}
